package com.li.springbootproject.config.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @Description：
 * @Author：LiDong
 * @Create：2021/4/1
 * @Version：1.0.0
 */
//@Aspect
//@Order(1)
//@Component
public class DataSourceAspect {
    private final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 切点：注解定义的方法都会被拦截
     */
    @Pointcut("@annotation(com.li.springbootproject.config.datasource.MyDataSource)")
    public void dsPointCut() {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MyDataSource dataSource = method.getAnnotation(MyDataSource.class);
        if (dataSource != null) {
            // 设置切换数据源
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

}